const md5 = require("md5");
const {
    getUsers,
    getUser,
    addUser,
    deleteUser,
    updateUser,
} = require("../model/user");

// 获取用户列表
const GetUsers = async (ctx) => {
    const users = await getUsers();
    ctx.body = {
        code: 200,
        msg: "获取用户列表成功",
        data: users,
    };
};

// 获取用户信息
const GetUser = async (ctx) => {
    const { id } = ctx.params;
    const user = await getUser(id);
    ctx.body = {
        code: 200,
        msg: "获取用户信息成功",
        data: user,
    };
};

// 添加用户
const AddUser = async (ctx) => {
    const { username, password } = ctx.request.body;
    const user = await addUser(username, md5(password));
    ctx.body = {
        code: 200,
        msg: "添加用户成功",
        data: user,
    };
};

// 删除用户
const DeleteUser = async (ctx) => {
    const { id } = ctx.params;
    const user = await deleteUser(id);
    ctx.body = {
        code: 200,
        msg: "删除用户成功",
        data: user,
    };
};

// 更新用户信息
const UpdateUser = async (ctx) => {
    const { password, is_delete } = ctx.request.body;
    const update = {};
    if (password !== undefined) {
        update.password = md5(password);
    }
    if (is_delete !== undefined) {
        update.is_delete = is_delete;
    }
    const data = await updateUser(ctx.params.id, update);
    ctx.body = {
        code: 200,
        msg: "更新用户信息成功",
        data,
    };
};

module.exports = {
    GetUsers,
    GetUser,
    AddUser,
    DeleteUser,
    UpdateUser,
};
